<template>
  <el-select
    v-model="l_retailid"
    filterable
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="retailSearch"
    :loading="loading"
    :disabled="disabled"
    @change="selectChanged"
  >
    <el-option v-for="item in retails" :key="item.AutoId" :label="item.Name" :value="item.AutoId">
      <span style="float: left">{{ item.Name }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.Code }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { listRetail } from '@/api/retail'

export default {
  data() {
    return {
      loading: false,
      retails: [],
      l_retailid: null
    }
  },
  model: {
    prop: 'retailId',
    event: 'retailSelected'
  },
  props: ['retailId', 'disabled', 'autocheck'],
  mounted() {
    this.search('%', data => {
      if (this.autocheck && !this.retailId) {
        this.$emit('retailSelected', data[0].AutoId, data[0])
        this.l_retailid = data[0].AutoId
      }
    })
    if (this.retailId) {
      this.l_retailid = this.retailId
    }
  },
  watch: {
    retailId: function(value) {
      this.l_retailid = value
    }
  },
  methods: {
    search(keywords, complete) {
      const cond = [
        {
          Key: 'Name',
          Op: 'like',
          Value: keywords
        }
      ]
      listRetail(0, 50, cond)
        .then(response => {
          this.retails = response.Data
          if (complete) {
            complete(this.retails)
          }
        })
        .catch(error => {
          console.log(error)
          this.retails = []
        })
    },
    retailSearch(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.search(query)
        }, 200)
      } else {
        this.retails = []
      }
    },
    selectChanged(params) {
      console.log(params)
      this.$emit('retailSelected', params)
    }
  }
}
</script>